
/**
 * Kohive.app.InviteController
 * @extends ExtMVC.Controller
 * Manages the invites section of the site
 */
Kohive.app.InviteController = Ext.extend(Kohive.controllers.KohiveController, {
	name		: 'invite',
	title		: Ext.ux.Translator.translate('invite_users'),

	constructor	: function() {
		Kohive.app.InviteController.superclass.constructor.call(this, {
					viewsPackage	: Kohive.views.invite
				});

		// TODO: This is a relic of old MVC, remove it once on ExtMVC 0.6 or above
		this.registerAction('index', this.index);
		// this.registerAction('refresh', this.onRefresh);

		this.initEvents();
	},

	initEvents	: function() {
		this.addEvents(
				/**
		 * @event import-successful
		 * fires whe
		 * n an import was successful
		 */
				'import-successful',

				/**
				* @event import-failed
				* fires when an import failed
				*/
				'import-failed'
		);
	},

	/**
	 * @action index 
	 * Renders the index view
	 */
	index		: function(contact) {
		if (!contact)
			return;

		if (this.indexWindow) {
			this.indexWindow.contact = contact;
			this.indexWindow.show();
			return;
		};

		this.indexWindow = this.renderView('index', {
					contact		: contact,
					closeAction	: 'hide',
					autoShow	: true,
					listeners	: {
						'import-contacts'	: {
							scope	: this,
							fn		: this.onImport
						}
					}
				});

		this.indexWindow.show();
	},

	/**
	 * Imports all the records
	 */
	onImport	: function(records) {
		// make a string of all the records emails
		var str;

		Ext.each(records, function(record) {
			str = (str) ? str + " " + record.get('email') : record.get('email');
		}, this
		);

		// Create a new membership from the above values
		var membership = new Kohive.models.Membership({
					'email'		: str,
					'hive_id'	: Kohive.OS.getCurrentHiveId()
				});

		var controller = this;

		// Attempt to save the membership to the server
		membership.save({
					scope	: this,
					success	: function() {
						controller.indexWindow.hideLoading();
						controller.indexWindow.hide();
					},
					failure	: function() {
						controller.indexWindow.showFailure();
					}
				});
	}
}
);

ExtMVC.OS.getOS().registerController('invite', Kohive.app.InviteController);